package pass

import (
	"strings"

	"github.com/gin-gonic/gin"
)

// 拦截配置结构体
type InterceptConfig struct {
	Paths   []string // 需要拦截的路径
	Methods []string // 需要拦截的HTTP方法
	Code    int      // 拦截后返回的状态码
}

// NewInterceptMiddleware 创建一个拦截中间件，拦截指定路径和方法的请求并返回指定状态码
func (config *InterceptConfig) NewInterceptMiddleware() gin.HandlerFunc {
	// 规范化路径和方法，转为小写便于比较
	normalizedPaths := make([]string, len(config.Paths))
	for i, path := range config.Paths {
		// 确保路径以"/"开头
		if !strings.HasPrefix(path, "/") {
			normalizedPaths[i] = "/" + path
		} else {
			normalizedPaths[i] = path
		}
	}

	normalizedMethods := make([]string, len(config.Methods))
	for i, method := range config.Methods {
		normalizedMethods[i] = strings.ToUpper(method)
	}

	return func(c *gin.Context) {
		// 检查当前请求路径是否在拦截列表中
		pathMatch := false
		for _, path := range normalizedPaths {
			if c.Request.URL.Path == path {
				pathMatch = true
				break
			}
		}

		// 检查当前请求方法是否在拦截列表中
		methodMatch := false
		if pathMatch {
			currentMethod := c.Request.Method
			for _, method := range normalizedMethods {
				if currentMethod == method {
					methodMatch = true
					break
				}
			}
		}

		// 如果路径和方法都匹配，则直接返回指定状态码
		if pathMatch && methodMatch {
			c.Status(config.Code)
			c.Abort() // 终止后续处理
			return
		}

		// 不匹配则继续处理
		c.Next()
	}
}

func NewInterceptConfig() *InterceptConfig {
	return &InterceptConfig{
		Paths:   []string{},
		Methods: []string{},
		Code:    200,
	}
}
